<template>

  <view class="container">

    <view class="form-container">
      <up-form labelPosition="left" :model="upfixFormData" ref="form1" class="form" :labelStyle="{paddingLeft:'20rpx'}">


        <!-- 故障区域  -->
        <up-form-item label="故障区域" labelWidth="150rpx" borderBottom ref="item1" class="form-item">
          <view class="inputshow">
            <view class="inputshow" @click="onclick1">
              <up-input :placeholder="upfixFormData.faultArea" class="up-input" disabled />
            </view>
          </view>
        </up-form-item>


        <up-form-item label="故障地址" labelWidth="150rpx" borderBottom ref="item1" class="form-item">
          <up-input :value="upfixFormData.faultadd" placeholder="请输入或选择故障详细地址" class="up-input" disabled />
        </up-form-item>


        <up-form-item label="维修项目" labelWidth="150rpx" borderBottom ref="item1" class="form-item">

          <view>
            <view class="inputshow" @click="onclick2">
              <up-input :placeholder=" upfixFormData.repairProject" class="up-input" disabled />
            </view>
          </view>
        </up-form-item>


        <up-form-item label="故障描述" labelWidth="150rpx" borderBottom ref="item1" class="form-item">
          <!--  <up-textarea :value="upfixFormData.faultDescription" placeholder="请详尽填写故障描述，字符长度6-200字" count autoHeight
            class="up-textarea" maxlength="200" readonly /> -->
          <up-input :placeholder=" upfixFormData.faultDescription" class="up-input" disabled />
        </up-form-item>

        <up-form-item label="故障照片" labelWidth="150rpx" borderBottom ref="item1" class="form-item">

          <view class="album">
            <up-album :urls="urls2" class="albumItem"></up-album>

          </view>
        </up-form-item>
        <!-- 上面的自动读取，无需输入 -->

        <up-divider></up-divider>

        <!-- 维修师傅需要做的事，也从账号中获取信息，无需手动填入 -->

        <up-form-item label="承接单位" labelWidth="150rpx" borderBottom ref="item1" class="form-item">
          <up-input :value="upfixFormData.faultAnalysis" placeholder="一般维修" class="up-input" />
        </up-form-item>
        <up-form-item label="维修师傅" labelWidth="150rpx" borderBottom ref="item1" class="form-item">
          <up-input :value="upfixFormData.faultAnalysis" placeholder="李师傅" class="up-input" />
        </up-form-item>
        <up-form-item label="电话号码" labelWidth="150rpx" borderBottom ref="item1" class="form-item">
          <up-input :value="upfixFormData.faultAnalysis" placeholder="一般维修" class="up-input" color="#00ff7f" />
        </up-form-item>
        <up-form-item label="收费地址" labelWidth="150rpx" borderBottom ref="item1" class="form-item">
          <up-input :value="upfixFormData.faultAnalysis" placeholder="一般维修" class="up-input" />
        </up-form-item>

        <up-divider></up-divider>


        <!-- 手动填入的信息 -->
        <up-form-item label="故障分析" labelPosition="top" labelWidth="150rpx" borderBottom ref="item1" class="form-item">
          <up-input :value="upfixFormData.faultAnalysis" placeholder="一般维修" class="up-input" />
        </up-form-item>


        <up-form-item label="维修完成拍照" labelPosition="top" labelWidth="200rpx" borderBottom ref="item1" class="form-item">
          <view class="up-upload">
            <up-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
              :maxCount="10"></up-upload>
          </view>
        </up-form-item>


      </up-form>
      <up-button type="primary" text="上传提交" @click="submitForm" class="submit-button"></up-button>
    </view>
  </view>
</template>

<script setup>
  import {
    computed,
    onMounted,
    reactive
  } from 'vue';


  const urls2 = ref([
    'https://pic4.zhimg.com/v2-14098590ffdbf8a4a3e0db52c07fdded_r.jpg?source=1940ef5c',
    'https://pic4.zhimg.com/v2-14098590ffdbf8a4a3e0db52c07fdded_r.jpg?source=1940ef5c',
    'https://pic4.zhimg.com/v2-14098590ffdbf8a4a3e0db52c07fdded_r.jpg?source=1940ef5c',
    'https://pic4.zhimg.com/v2-14098590ffdbf8a4a3e0db52c07fdded_r.jpg?source=1940ef5c',

  ]);

  // -----------解决导航栏遮住表单的问题  -------------------

  // import {
  //   useSystemInfoStore
  // } from "@/store/systemInfo.js"
  // import {
  //   storeToRefs
  // } from 'pinia';

  // //pinia中解构赋值会是失去响应式   -- html模版不需要value
  // const {
  //   navBarHeight,
  //   statusBarHeight
  // } = storeToRefs(useSystemInfoStore());

  // console.log(navBarHeight, statusBarHeight)

  // const marginTopNum = computed(() => {
  //   return Number(navBarHeight.value) + Number(statusBarHeight.value);
  // });

  // console.log('marginTop.value: ', marginTopNum.value);

  // onLaunch(() => {
  //   console.log('App Launch')

  // })
  // onShow(() => {
  //   console.log('App onShow')
  // })




  // -------------------------



  const upfixFormData = reactive({
    faultadd: "请输入或选择故障详细地址",
    faultArea: "请选择故障区域和楼宇", // 把选择的值加入
    repairProject: "请选择维修项目", // 同上
    faultDescription: "请详尽填写故障描述，字符长度6-200字", // 文本描述
    faultPhotos: [], // 初始化为空数组
    faultAnalysis: "一般维修",
    fixPhoyos: []
  })

  // const onKeyInput = (event) => {
  //   this.inputValue = event.target.value
  // }

  //
  const cancel = () => {
    show.value = false;
    show2.value = false;
  }

  const closed = () => {
    show.value = false;
    show2.value = false;
  }

  //pick维修地址
  const show = ref(false);
  // const selectValue = ref("请选择故障区域和楼宇")
  const addColumns = reactive([
    ['中国', '美国'],
    ['深圳', '厦门', '上海', '拉萨']
  ]);
  const addColumnData = reactive([
    ['深圳', '厦门', '上海', '拉萨'],
    ['得州', '华盛顿', '纽约', '阿拉斯加']
  ])
  const uPickerRef = ref(null)

  const onclick1 = () => {
    show.value = true
  }
  const changeHandler = (e) => {
    const {
      columnIndex,
      value,
      values,
      index,
    } = e;

    if (columnIndex === 0) {
      uPickerRef.value.setColumnValues(1, addColumnData[index]);
    }
  };

  const confirm = (e) => {
    console.log('confirm', e);
    upfixFormData.faultArea = e.value.join('/');

    // selectValue.value = e.value.join('/');
    // console.log('selectValue', selectValue.value);
    show.value = false;
  };
  //维修项目

  const show2 = ref(false);
  // const selectValue2 = ref("请选择维修项目")
  const fixProjectColumns = reactive([
    ['中国', '美国'],
    ['深圳', '厦门', '上海', '拉萨']
  ]);
  const fixProjectColumnData = reactive([
    ['深圳', '厦门', '上海', '拉萨'],
    ['得州', '华盛顿', '纽约', '阿拉斯加']
  ]);

  const onclick2 = () => {
    show2.value = true
  }
  const uPickerRef2 = ref(null)
  const changeHandler2 = (e) => {
    const {
      columnIndex,
      value,
      values,
      index,
    } = e;

    if (columnIndex === 0) {
      uPickerRef2.value.setColumnValues(1, fixProjectColumnData[index]);
    }
  };

  const confirm2 = (e) => {
    console.log('confirm', e);
    upfixFormData.repairProject = e.value.join('/');
    // selectValue2.value = e.value.join('/');
    // console.log('selectValue', selectValue2.value);
    show2.value = false;
  };

  //故障描述
  // const value2 = ref('请详尽填写故障描述，字符长度6-200字');


  //------------------上传照片----------------------


  const fileList1 = ref([]);

  // 删除图片
  const deletePic = (event) => {
    fileList1.value.splice(event.index, 1);
  };

  // 新增图片
  const afterRead = async (event) => {
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    let lists = [].concat(event.file);
    let fileListLen = fileList1.value.length;
    lists.map((item) => {
      fileList1.value.push({
        ...item,
        status: 'uploading',
        message: '上传中',
      });
    });
    for (let i = 0; i < lists.length; i++) {
      const result = await uploadFilePromise(lists[i].url);
      let item = fileList1.value[fileListLen];
      fileList1.value.splice(fileListLen, 1, {
        ...item,
        status: 'success',
        message: '',
        url: result,
      });
      fileListLen++;
    }
  };

  const uploadFilePromise = (url) => {
    return new Promise((resolve, reject) => {
      let a = uni.uploadFile({
        url: 'http://192.168.2.21:7001/upload', // 仅为示例，非真实的接口地址
        filePath: url,
        name: 'file',
        formData: {
          user: 'test',
        },
        success: (res) => {
          setTimeout(() => {
            resolve(res.data.data);
          }, 1000);
        },
      });
    });
  };


  //提交

  // 整合表单数据并提交
  const submitForm = async () => {
    console.log("开始上传")
    // 确保所有图片上传完成
    // 这里简单示例，实际应考虑更完善的上传状态检查
    while (fileList1.value.some(item => item.status !== 'success')) {
      await new Promise(resolve => setTimeout(resolve, 100)); // 等待上传完成
    }

    // 将所有数据整合，包括上传成功的图片URL
    const formDataToSend = {
      ...upfixFormData,
      faultPhotos: fileList1.value.filter(item => item.status === 'success').map(item => item.url),
    };

    try {
      const response = await uni.request({
        url: '你的后端提交接口URL',
        method: 'POST',
        data: formDataToSend,
        header: {
          'Content-Type': 'application/json',
        },
      });

      if (response.statusCode === 200) {
        console.log('表单提交成功');
        // 提交成功后的处理，如提示用户、清空表单等
      } else {
        console.error('表单提交失败');
      }
    } catch (error) {
      console.error('提交过程中发生错误', error);
    }
  };
</script>

<style lang="scss">
  page {
    margin: 0;
    padding: 0;
  }

  .container {
    width: 100vw;
    height: 100vh;
    background-color: #fff;

    .form-container {
      width: 94%;
      margin: 0 auto;
      padding: 0 auto;

      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

      .form {
        width: 100%;
        height: 100%;
        padding: 0 5rpx;

        .form-item {
          padding: 5rpx;

          .album {
            width: 90vw;
            padding-left: 10rpx;



          }
        }


        //   // 输入框和文本区域样式
        .up-input,
        .up-textarea {
          height: 60rpx;
          background-color: #ffffff;
          color: black;
          border-radius: 4rpx;
          padding: 8rpx 12px;
          font-size: 14rpx;
        }

        .up-input-active,
        .up-textarea-activate {
          height: 60rpx;
          background-color: #f5f5f5;
          border-radius: 4rpx;
          padding: 8rpx 12rpx;

          font-size: 14rpx;
        }


        // 故障照片上传样式
        .up-upload {
          margin-top: 10rpx;
          margin-bottom: 10rpx;
        }


      }

      .submit-button {
        // 提交按钮样式
        width: 100%;
        height: 48rpx;
        background-color: #2d8cf0;
        color: #fff;
        border-radius: 4rpx;
        font-size: 16rpx;
        margin-top: 10rpx;
        display: flex;
        justify-content: center;
        align-items: center;

        &:active {
          opacity: 0.8;
        }
      }


    }

  }
</style>